﻿using DeHeng_Mes.Model.Table;
using GXWA_DATA.Dao;
using GXWA_DATA.Model.Table;
using GXWA_DATA.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GXWA_DATA.Model.Singleton
{
    public sealed class ProductionSingleton
    {
        #region 成员实例
        private static DataDao dataDao = new DataDao();
        #endregion

        private static readonly Lazy<List<TraceProduction>> _instance = new Lazy<List<TraceProduction>>(() => new List<TraceProduction>());

        public static List<TraceProduction> Instance => _instance.Value;

        public ProductionSingleton() { }

        /// <summary>
        /// 缓存
        /// </summary>
        /// <param name="production"></param>
        public static void Add(TraceProduction production)
        {
            Instance.Add(production);

            Tools.ProduceLogText($"[{production.OrderId}]产量缓存成功，工位号[{production.Station}]，产量[{production.ProductionNum}]，NG产量[{production.ProductionNg}]");
        }

        /// <summary>
        /// 清除缓存
        /// </summary>
        /// <param name="orderId"></param>
        public static void ClearByOrder(string orderId)
        {
            List<TraceProduction> traceProductions = Instance.Where(x => x.OrderId == orderId).ToList();

            traceProductions.ForEach(x => Instance.Remove(x));

            Tools.ProduceLogText($"[{orderId}]清除产量缓存成功，清除条目[{traceProductions.Count}]条");
        }

        /// <summary>
        /// 更新产量
        /// </summary>
        /// <param name="station"></param>
        /// <param name="orderId"></param>
        public static int AddProduction(string station, string orderId)
        {
            int count = Instance.First(x => x.OrderId == orderId && x.Station == station).ProductionNum ++;

            dataDao.UpdateProduction(orderId, station, count);

            Tools.ProduceLogText($"[{station}]工位产量更新，当前产量[{count}]，关联工单[{orderId}]");

            return count;
        }

        /// <summary>
        /// 更新NG产量
        /// </summary>
        /// <param name="station"></param>
        /// <param name="orderId"></param>
        public static int AddNgProduction(string station, string orderId)
        {
            int count = Instance.First(x => x.OrderId == orderId && x.Station == station).ProductionNg++;

            dataDao.UpdateNgProduction(orderId, station, count);

            Tools.ProduceLogText($"[{station}]工位产量更新，当前NG产量[{count}]，关联工单[{orderId}]");

            return count;
        }
    }
}
